package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.entity.Department;
import com.demo.entity.Patient;
import com.demo.entity.PhysicalPreventionLog;
import com.demo.enums.PatientStatusEnum;
import com.demo.mapper.DepartmentMapper;
import com.demo.mapper.PatientMapper;
import com.demo.mapper.PhysicalPreventionLogMapper;
import com.demo.response.Result;
import com.demo.service.IPhysicalPreventionLogService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PhysicalPreventionLogServiceImpl extends ServiceImpl<PhysicalPreventionLogMapper, PhysicalPreventionLog> implements IPhysicalPreventionLogService {

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    PatientMapper patientMapper;

    @Resource
    PhysicalPreventionLogMapper physicalPreventionLogMapper;

    @Override
    public Result physicalList(Integer pageNumber, Integer pageSize, Integer wardId) {
        DecimalFormat df = new DecimalFormat("0.00");
        List<Integer> wardList = new ArrayList<>();
        if (wardId == null) {
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper();
            departmentQueryWrapper.eq("1", 1);
            List<Department> departmentList = departmentMapper.selectList(departmentQueryWrapper);
            for (Department item : departmentList) {
                wardList.add(item.getDeptMapping());
            }
        } else {
            wardList.add(wardId);
        }
        Page<Patient> page = new Page(pageNumber.intValue(), pageSize.intValue());
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper();
        patientQueryWrapper.ne("status", PatientStatusEnum.CHU_YUAN.getValue());//非出院病人
        patientQueryWrapper.in("ward_id", wardList);
        patientQueryWrapper.isNull("deleted_time");
        patientQueryWrapper.orderByDesc("patient_id");
        IPage<Patient> iPage = patientMapper.selectPage(page, patientQueryWrapper);
        List<Map<String, Object>> bedPatient = new ArrayList();
        for (Patient item : iPage.getRecords()) {
            Map<String, Object> newItem = BeanUtil.beanToMap(item);
            // 查询患者总治疗时间和总治疗次数
            Map<String, Integer> total = physicalPreventionLogMapper.getTotalHourAndTimes(item.getPatientId(), null, null);
            newItem.put("total_hours", total.get("totalHour") == null ? 0 : df.format(((total.get("totalHour")).intValue() / 60.0F)));
            newItem.put("total_times", total.get("countNumber") == null ? 0 : total.get("countNumber"));
            newItem.put("today_number", total.get("countNumber") == null ? 0 : total.get("countNumber"));

            // 查询患者是否有正在进行中的治疗，如果有统计本次治疗的时间
            PhysicalPreventionLog ongoingTreatment = physicalPreventionLogMapper.getOngoingTreatmentByPatientId(item.getPatientId(), new Date());
            newItem.put("today_hours", ongoingTreatment == null ? 0 : 0.5);
            bedPatient.add(newItem);
        }
        PageInfo<Patient> pageInfo = new PageInfo(bedPatient);
        pageInfo.setTotal(iPage.getTotal());
        pageInfo.setPages((int) iPage.getPages());
        if (pageNumber.equals(Long.valueOf(iPage.getPages()))) {
            pageInfo.setIsLastPage(false);
        } else {
            pageInfo.setIsLastPage(true);
        }
        return Result.success(pageInfo);
    }

    @Override
    public Result addPhysicalLog(PhysicalPreventionLog physicalPreventionLog) {
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper();
        patientQueryWrapper.select(new String[]{"patient_id"});
        patientQueryWrapper.eq("patient_id", physicalPreventionLog.getHisPatientId());
        Patient patient = patientMapper.selectOne(patientQueryWrapper);
        if (patient != null) {
            physicalPreventionLog.setPatientId(patient.getPatientId());
            save(physicalPreventionLog);
        }
        return Result.success();
    }

    @Override
    public Result updatePhysicalLogStop(Integer vte_preventive_id, Date stop_time) {
        QueryWrapper<PhysicalPreventionLog> physicalPreventionLogQueryWrapper = new QueryWrapper();
        physicalPreventionLogQueryWrapper.eq("vte_preventive_id", vte_preventive_id);
        physicalPreventionLogQueryWrapper.orderByDesc("physical_prevention_id");
        physicalPreventionLogQueryWrapper.last("limit 1");
        PhysicalPreventionLog physicalPreventionLog = physicalPreventionLogMapper.selectOne(physicalPreventionLogQueryWrapper);
        UpdateWrapper<PhysicalPreventionLog> physicalPreventionLogUpdateWrapper = new UpdateWrapper();
        physicalPreventionLogUpdateWrapper.set("end_time", stop_time);
        physicalPreventionLogUpdateWrapper.set("updated_time", stop_time);
        physicalPreventionLogUpdateWrapper.eq("physical_prevention_id", physicalPreventionLog.getPhysicalPreventionId());
        update(physicalPreventionLogUpdateWrapper);
        return Result.success();
    }
}
